package com.coffee.coffeetool.app;

import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author liuyueheng
 * @date 16/11/3.
 */
public class MyApplication extends Application {
    // singleton
    private static MyApplication context = null;

    //App的上下文
    public static Context mContext = null;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        mContext = this;
        AppManager.initialize(this);
    }


    /**
     * 保存磁盘缓存
     *
     * @param key
     * @param value
     * @throws IOException
     */
    public void setDiskCache(String key, String value) throws IOException {
        FileOutputStream fos = null;
        try {
            fos = openFileOutput("cache_" + key + ".data", MODE_PRIVATE);
            fos.write(value.getBytes());
            fos.flush();
        } finally {
            try {
                if (fos != null) fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取磁盘缓存数据
     *
     * @param key
     * @return
     * @throws IOException
     */
    public String getDiskCache(String key) throws IOException {
        FileInputStream fis = null;
        try {
            fis = openFileInput("cache_" + key + ".data");
            byte[] datas = new byte[fis.available()];
            fis.read(datas);
            return new String(datas);
        } catch (FileNotFoundException e) {
            //StatWrapper.recordException(mContext,e); 忽略openFileInput抛出的异常上传日志
            try {
                if (fis != null) fis.close();
            } catch (Exception e1) {
                e.printStackTrace();
            }
        } finally {
            try {
                if (fis != null) fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // 配置MultiDex(第五步)
        // 将MultiDex注入到项目中
    }

    public static MyApplication getInstance() {
        return context;
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //保存系统选择语言
    }
}
